package logic

import (
	"context"
	"fmt"
	"user_srv/models/mysql"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealNameLogic {
	return &RealNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RealNameLogic) RealName(in *user.RealNameRequest) (*user.RealNameResponse, error) {
	// todo: add your logic here and delete this line
	//new_id_number = id_number[:6] + "******" + id_number[-4:]
	names := mysql.RealName{}
	err := names.RealNameInfo(in.UserId, in.RealName)
	if err != nil {
		logx.Error("实名认证信息错误")
		return nil, fmt.Errorf("实名认证信息错误")
	}
	if names.ID != 0 {
		logx.Error("用户实名已实名，请重新实名")
		return nil, fmt.Errorf("用户实名已实名，请重新实名")
	}
	names.UserId = in.UserId
	names.RealName = in.RealName
	names.IdCord = in.IdCord

	if len(names.IdCord) >= 14 {
		names.IdCord = names.IdCord[:6] + "******" + names.IdCord[12:]
	}
	if !pkg.RealName(in.IdCord, in.RealName) {
		logx.Error("第三方实名错误")
		return nil, fmt.Errorf("第三方实名错误")
	}
	err = names.CreateInfo()
	if err != nil {
		logx.Error("保存实名认证失败")
		return nil, fmt.Errorf("保存实名认证失败")
	}
	return &user.RealNameResponse{}, nil
}
